package com.infra.micro.id.domain.repository;

import com.infra.common.util.ConvertUtils;
import com.infra.micro.id.domain.entity.IdAppPO;
import com.infra.micro.id.domain.entity.IdAppExample;
import com.infra.micro.id.domain.mapper.IdAppMapper;
import com.infra.micro.id.model.req.QueryIdTokenByCondReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class IdAppRepository {
    @Resource
    private IdAppMapper idAppMapper;

    public IdAppPO queryByAppId(Integer appId) {
        return idAppMapper.selectByPrimaryKey(appId);
    }

    public int update(IdAppPO record) {
        return idAppMapper.updateByPrimaryKeySelective(record);
    }

    public int insert(IdAppPO record) {
        return idAppMapper.insertSelective(record);
    }

    public int deleteById(Integer appId) {
        return idAppMapper.deleteByPrimaryKey(appId);
    }

    public int batchDeleteByIds(List<Integer> appIds) {
        IdAppExample example = new IdAppExample();
        example.createCriteria().andAppIdIn(appIds);
        return idAppMapper.deleteByExample(example);
    }

    public List<IdAppPO> querySimpleList() {
        IdAppExample example = new IdAppExample();
        example.createCriteria().andIsDisabledEqualTo(false);
        return idAppMapper.selectByExample(example);
    }

    public List<IdAppPO> queryList(QueryIdTokenByCondReq req) {
        IdAppExample example = new IdAppExample();
        IdAppExample.Criteria criteria = example.createCriteria();
        if (req != null) {
            return idAppMapper.selectByExample(example);
        }

        Integer appId = ConvertUtils.parseInteger(req.getAppId());
        if (appId != null) {
            criteria.andAppIdEqualTo(appId);
        }

        String appName = ConvertUtils.parseString(req.getAppName());
        if (StringUtils.isNotBlank(appName)) {
            criteria.andAppNameLike("%" + appName + "%");
        }

        String deptName = ConvertUtils.parseString(req.getDeptName());
        if (StringUtils.isNotBlank(appName)) {
            criteria.andDeptNameLike("%" + deptName + "%");
        }

        String ownerName = ConvertUtils.parseString(req.getOwnerName());
        if (StringUtils.isNotBlank(ownerName)) {
            criteria.andOwnerNameLike("%" + ownerName + "%");
        }

        String ownerEmail = ConvertUtils.parseString(req.getOwnerEmail());
        if (StringUtils.isNotBlank(ownerEmail)) {
            criteria.andOwnerEmailLike("%" + ownerEmail + "%");
        }

        Boolean disabled = ConvertUtils.parseBoolean(req.getDisabled());
        if (disabled != null) {
            criteria.andIsDisabledEqualTo(disabled);
        }
        return idAppMapper.selectByExample(example);
    }
}
